package com.fadadianqi.logistics.admin.staff.service;

import com.fadadianqi.logistics.admin.staff.dao.ActionDAO;
import com.fadadianqi.logistics.admin.staff.model.Action;
import com.fadadianqi.cache.Cache;
import com.fadadianqi.cache.CacheFactory;
import com.fadadianqi.commons.PrimaryKeyCreator;
import com.yeqiangwei.commons.util.ValidatorHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ActionService {

    private Cache cache = CacheFactory.getCache("staff");

    /**
     * 系统启动后初始化权限表
     */
    public void init() {
        ActionEnum[] es = ActionEnum.values();
        for (ActionEnum ae : es) {
            String id = ae.toString();
            Action a = actionDAO.getById(id);
            if (a == null) {
                a = new Action();
                a.setId(id);
                a.setName(ActionMap.getName(ae));
                actionDAO.create(a);
            }
        }

        //
        List<Action> actions = this.findAll();
        if (!ValidatorHelper.isEmpty(actions)) {
            for (Action a : actions) {
                if (ActionMap.getName(a.getId()) == null) {
                    actionDAO.remove(a);
                }
            }
        }
        // 初始化管理员

    }

    public List<Action> findAll() {
        List<Action> list = (List<Action>) cache.get("actions");
        if (ValidatorHelper.isNotEmpty(list)) {
            return list;
        }
        list = actionDAO.findAll();
        cache.set("actions", list);
        return list;
    }

    public void save(Action action) {
        if (ValidatorHelper.isEmpty(action.getId())) {
            action.setId(PrimaryKeyCreator.create());
            actionDAO.create(action);
        } else {
            actionDAO.update(action);
        }
        cache.del("actions");
        cache.del("action_" + action.getId());
    }

    public Action getById(String id) {
        Action action = (Action) cache.get("action_" + id);
        if (action != null) {
            return action;
        }
        action = actionDAO.getById(id);
        cache.set("action_" + id, action);
        return action;
    }

    @Autowired
    private ActionDAO actionDAO;
}
